package com.springboot.astra.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.astra.bean.Carousel;
import com.springboot.astra.bean.Goods;
import com.springboot.astra.bean.Goodstag;
import com.springboot.astra.bean.Tag;
import com.springboot.astra.result.DataResult;
import com.springboot.astra.service.CarouselService;
import com.springboot.astra.service.GoodsService;
import com.springboot.astra.service.GoodstagService;
import com.springboot.astra.service.TagService;
import com.springboot.astra.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodstagService goodstagService;

    @Autowired
    private CarouselService carouselService;

    @Autowired
    TagService tagService;

    private String coverPath;

    /**
     * 通过id查找一个商品信息，返回一个goods类
     * @param
     * @return
     */
    @PostMapping("/getOneGoods")
    public DataResult getUserById(@RequestParam Map<String,String> map){
        Goods goods = goodsService.getOneById(Integer.valueOf(map.get("goodsId")));
        goods.setCarousels(goodsService.getCarousels(goods.getGoodsId()));
        goods.setTags(goodsService.getTags(goods.getGoodsId()));
        return DataResult.success(goods);
    }

    /**
     * 查找所有商品
     * @return
     */
    @PostMapping("/getAllGoods")
    public DataResult getAll(@RequestParam Map<String,String> map){
        //此次查询不需要获取商品的轮播图和标签属性，具体属性在商品详情里显示
        String query = map.get("query");
        Integer pagenum = Integer.valueOf(map.get("pagenum"));
        Integer pagesize = Integer.valueOf(map.get("pagesize"));
        Page<Goods> page = new Page<Goods>(pagenum,pagesize);
        IPage<Goods> goodsList = goodsService.pageGoodsVo(page,query);
        return DataResult.success(goodsList);
    }

    /**
     * 为用户查商品
     * @param map
     * @return
     */
    @PostMapping("/getAllGoodsForUser")
    public DataResult getAllGoodsForUser(@RequestParam Map<String,String> map){
        //此次查询不需要获取商品的轮播图和标签属性，具体属性在商品详情里显示
        String query = map.get("query");
        Integer pagenum = Integer.valueOf(map.get("pagenum"));
        Integer pagesize = Integer.valueOf(map.get("pagesize"));
        Page<Goods> page = new Page<Goods>(pagenum,pagesize);
        IPage<Goods> goodsList = goodsService.pageGoodsVoForUser(page,query);
        return DataResult.success(goodsList);
    }
    /**
     * 插入一个商品的基本属性
     */
    @PutMapping("/addGoods")
    @Transactional
    public DataResult insertGoods(@RequestBody Goods goods){
        //传入goods对象,只插入商品，轮播图和标签另写函数
        System.out.println(goods);
        goods.setDelete(true);
        goods.setCreateTime(DateUtils.getTime());
        goods.setUpdateTime(DateUtils.getTime());
        //注入进本属性，获取goodID
        goodsService.insertGoods(goods);
        Integer id = goods.getGoodsId();
        //注入商品标签
        List<Tag> tagList = goods.getTags();
        Iterator<Tag> iterator = tagList.iterator();
        while (iterator.hasNext()) {
            Goodstag goodstag = new Goodstag();
            goodstag.setGoodsId(id);
            goodstag.setTagId(iterator.next().getTagId());
            goodstagService.inserGoodsTag(goodstag);
        }
        //注入商品轮播图
        List<Carousel> carouselList = goods.getCarousels();
        Iterator<Carousel> iteratorCarousel = carouselList.iterator();
        while (iteratorCarousel.hasNext()) {
            Carousel carousel = new Carousel();
            carousel.setGoodsId(id);
            carousel.setUrl(iteratorCarousel.next().getUrl());
            carouselService.insertCarousel(carousel);
        }
        return DataResult.success();
    }
    @PutMapping("/addTagForGoods")
    public DataResult addTagForGoods(@RequestBody Goodstag goodstag) {
        //每次添加标签都进行次函数
        //此函数操作商品-标签表
        goodstagService.inserGoodsTag(goodstag);
        return DataResult.success();
    }
    @PutMapping("/addGoodsCarousel")
    public DataResult addGoodsCarousel(@RequestBody Carousel carousel){
        //每次上传都进行该函数
        carouselService.insertCarousel(carousel);
        return DataResult.success();
    }
    @PostMapping("/deleteOneGoodsCarousel")
    public DataResult deleteOneGoodsCarousel(@RequestParam Map<String,String> map){
        Integer cId = Integer.valueOf(map.get("cId"));
        carouselService.deleteOneById(cId);
        return DataResult.success();
    }
    /**
     * 删除一个商品的基本属性,系统不会删除任何商品信息，只是修改isDelete
     */
    @PutMapping("/updateGoods")
    public DataResult updateOneById(@RequestBody Goods goods){
        goods.setUpdateTime(DateUtils.getTime());
        goodsService.updateOneById(goods);
        return DataResult.success();
    }
    @PutMapping("/deleteGoods")
    public DataResult deleteGoods(@RequestBody Goods goods){
        goodsService.deleteOneById(goods);
        return DataResult.success();
    }

    @PostMapping("/getOneTag")
    public DataResult getOneTag(@RequestParam Map<String,String> map){
        Tag tag = tagService.getOneById(Integer.valueOf(map.get("tagId")));
        return DataResult.success(tag);
    }
    @PostMapping("/getAllTag")
    public DataResult getAllTag(@RequestParam Map<String,String> map){
        try {
            String query = map.get("query");
            Integer pagenum = Integer.valueOf(map.get("pagenum"));
            Integer pagesize = Integer.valueOf(map.get("pagesize"));
            Page<Tag> page = new Page<Tag>(pagenum, pagesize);
            IPage<Tag> tags= tagService.selectPageVo(page,query);
            return DataResult.success(tags);
        }catch (Exception e) {
            return DataResult.fail();
        }
    }

    /**
     * 获取所有tag标签以供添加
     * @return
     */
    @GetMapping("/getAllTagForInsert")
    public DataResult getAllTagForInsert() {
        List<Tag> tagList = tagService.getAll();
        return DataResult.success(tagList);
    }

    @PutMapping("/addTag")
    @Transactional
    public DataResult addTag(@RequestBody Tag tag){
        tag.setIsDelete(1);//1为可用，0为不可用
        tagService.insertTag(tag);
        return DataResult.success();
    }

    @PutMapping("/updateTag")
    public DataResult update(@RequestBody Tag tag){
        tagService.updateOneById(tag);
        return DataResult.success();
    }
    @PostMapping("/uploadCoverImg/coverImg")
    public DataResult uploadCoverImg(@RequestParam("coverImg") MultipartFile uploadFile ) throws Exception {
        //获得项目的类路径
        String path = ResourceUtils.getURL("classpath:").getPath();
        //空文件夹在编译时不会打包进入target中
        File uploadDir = new File(path+"/static/img/goods");
        if (!uploadDir.exists()) {
            System.out.println("上传头像路径不存在，正在创建...");
            uploadDir.mkdir();
        }
        if ( uploadFile != null) {
            //获得上传文件的文件名
            String oldName = uploadFile.getOriginalFilename();
            System.out.println("[上传的文件名]：" + oldName);
            //文件保存在static目录下的static/img/goods/
            File avatar = new File(path + "/static/img/goods/" , oldName);
            try {
                //保存图片
                uploadFile.transferTo(avatar);
                //返回成功结果，附带文件的相对路径
                return DataResult.success(200,"http://localhost:8080/static/img/goods/"+oldName,"上传成功");
            }catch (IOException e) {
                e.printStackTrace();
                return DataResult.failWithMsg("上传失败");
            }
        }else {
            System.out.println("上传的文件为空");
            return DataResult.failWithMsg("文件传输错误");
        }
    }

    /**
     * 上传轮播图
     * @param uploadFile
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadCarousel/carousel")
    public DataResult uploadCarousel(@RequestParam("carousel") MultipartFile uploadFile) throws Exception {
        //获得项目的类路径
        String path = ResourceUtils.getURL("classpath:").getPath();
        //空文件夹在编译时不会打包进入target中
        File uploadDir = new File(path+"/static/img/carousel");
        if (!uploadDir.exists()) {
            System.out.println("上传头像路径不存在，正在创建...");
            uploadDir.mkdir();
        }
        if ( uploadFile != null) {
            //获得上传文件的文件名
            String oldName = uploadFile.getOriginalFilename();
            System.out.println("[上传的文件名]：" + oldName);
            //我的文件保存在static目录下的avatar/user
            File avatar = new File(path + "/static/img/carousel/" , oldName);
            try {
                //保存图片
                uploadFile.transferTo(avatar);
                //返回成功结果，附带文件的相对路径
                return DataResult.success(200,"http://localhost:8080/static/img/carousel/"+oldName,"图片上传成功");
            }catch (IOException e) {
                e.printStackTrace();
                return DataResult.failWithMsg("上传失败");
            }
        }else {
            System.out.println("上传的文件为空");
            return DataResult.failWithMsg("文件传输错误");
        }
    }
}
